const express = require("express")
const t = express.Router();
const { verifyToken } = require("../middlewares/Auth");
const uuid= require("uuid")
// 文件上传
const multer  = require('multer')

const  storage = multer.diskStorage({
   destination:function(req,file,cb){
     cb(null,"./public/upload")
   },
   filename:function(req,file,cb){
      //获取文件的全称
      let filename = file.originalname
      // 截取后缀
      let extension = filename.substr(filename.lastIndexOf(".")+1).toLowerCase();
      // 随机数+后缀 组成文件名
      filename = uuid.v1()+"."+extension
     cb(null, filename)
   }
 })
//  设置limits 防止DOs攻击
const up = multer({ storage: storage ,limits:{}})
const upload = up.fields([{name:'file',maxCount:1}])

/******************/ 
t.post('/up',(req,res,next)=>{
   upload(req, res, function (err) {
      // 错误捕捉
      if (err instanceof multer.MulterError) {
        // 发生错误
      res.send({code:201,msg:'文件上传错误！'})
      } else if (err) {
        // 发生错误
      res.send({code:201,msg:'文件上传错误！'})
      }
      
      // 一切都好
    })
})













t.post('/test',(req,res,next)=>{
   console.log(req.headers)
   res.send({code:'200',msg:'返回数据!'})
})
t.post('/jstoken',(req,res,next)=>{
   const token = req.headers.token || "";
   console.log(verifyToken(token))
})

module.exports = t